package com.mdd.admin.controller;

import com.mdd.admin.aop.Log;
import com.mdd.admin.service.INetworkSalesVolumeService;
import com.mdd.admin.validate.commons.IdValidate;
import com.mdd.admin.validate.NetworkSalesVolumeCreateValidate;
import com.mdd.admin.validate.NetworkSalesVolumeUpdateValidate;
import com.mdd.admin.validate.NetworkSalesVolumeSearchValidate;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.vo.NetworkSalesVolumeListedVo;
import com.mdd.admin.vo.NetworkSalesVolumeDetailVo;
import com.mdd.common.core.AjaxResult;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.NetworkSalesVolume;
import com.mdd.common.export.NetworkSalesVolumeListedExport;
import com.mdd.common.util.ExcelUtils;
import com.mdd.common.validator.annotation.IDMust;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author luo26
 */
@RestController
@RequestMapping("api/volume")
@Api(tags = "网销客户管理")
public class NetworkSalesVolumeController {

    @Resource
    INetworkSalesVolumeService iNetworkSalesVolumeService;

    @GetMapping("/list")
    @ApiOperation(value="网销客户列表")
    public AjaxResult<PageResult<NetworkSalesVolumeListedVo>> list(@Validated PageValidate pageValidate,
                                                     @Validated NetworkSalesVolumeSearchValidate searchValidate) {
        PageResult<NetworkSalesVolumeListedVo> list = iNetworkSalesVolumeService.list(pageValidate, searchValidate);
        return AjaxResult.success(list);
    }

    @GetMapping("/detail")
    @ApiOperation(value="网销客户详情")
    public AjaxResult<NetworkSalesVolumeDetailVo> detail(@Validated @IDMust() @RequestParam("id") Integer id) {
        NetworkSalesVolumeDetailVo detail = iNetworkSalesVolumeService.detail(id);
        return AjaxResult.success(detail);
    }

    @Log(title = "网销客户新增")
    @PostMapping("/add")
    @ApiOperation(value="网销客户新增")
    public AjaxResult<Object> add(@Validated @RequestBody NetworkSalesVolumeCreateValidate createValidate) {
        iNetworkSalesVolumeService.add(createValidate);
        return AjaxResult.success();
    }

    @Log(title = "网销客户编辑")
    @PostMapping("/edit")
    @ApiOperation(value="网销客户编辑")
    public AjaxResult<Object> edit(@Validated @RequestBody NetworkSalesVolumeUpdateValidate updateValidate) {
        iNetworkSalesVolumeService.edit(updateValidate);
        return AjaxResult.success();
    }

    @Log(title = "网销客户删除")
    @PostMapping("/del")
    @ApiOperation(value="网销客户删除")
    public AjaxResult<Object> del(@Validated @RequestBody IdValidate idValidate) {
        iNetworkSalesVolumeService.del(idValidate.getId());
        return AjaxResult.success();
    }

//    @Log(title = "excel模板下载")
//    @GetMapping("/downLoadExcel")
//    @ApiOperation(value="excel模板下载")
//    public ResponseEntity<byte[]> downLoadExcel1() {
//        // 使用try-with-resources来确保资源正确关闭
//        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//             Workbook workbook = new XSSFWorkbook()) {
//
//            Class<NetworkSalesVolumeCreateValidate> clazz = NetworkSalesVolumeCreateValidate.class;
//            Sheet sheet = workbook.createSheet("网销客户");
//
//            Field[] declaredFields = clazz.getDeclaredFields();
//            Row headerRow = sheet.createRow(0);  // 将表头行的索引改为0
//            int cellIndex = 0;
//
//            // 遍历字段并获取@ApiModelProperty注解的value值
//            for (Field declaredField : declaredFields) {
//                ApiModelProperty annotation = declaredField.getAnnotation(ApiModelProperty.class);
//                if (annotation != null) {
//                    String headerName = annotation.value();
//                    headerRow.createCell(cellIndex++).setCellValue(headerName);
//                }
//            }
//
//            // 自动调整列宽
//            for (int i = 0; i < declaredFields.length; i++) {
//                sheet.autoSizeColumn(i);
//            }
//
//            // 将工作簿内容写入 ByteArrayOutputStream
//            workbook.write(byteArrayOutputStream);
//
//            byte[] bytes = byteArrayOutputStream.toByteArray();
//
//            // 设置响应头
//            HttpHeaders headers = new HttpHeaders();
//            headers.set("Content-Disposition", "attachment; filename=network_sales_volume_template.xlsx");
//            headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//
//            // 返回文件数据，使用 ResponseEntity 包装返回
//            return ResponseEntity.ok()
//                    .headers(headers)
//                    .body(bytes);
//
//        } catch (IOException e) {
//            // 使用日志记录异常
//            // Logger logger = LoggerFactory.getLogger(ExcelDownloadController.class);
//            // logger.error("Excel 文件生成失败", e);
//            return ResponseEntity.status(500).body("文件生成失败".getBytes());
//        }
//    }

    @Log(title = "excel模板下载")
    @GetMapping("/downLoadExcel")
    @ApiOperation(value="excel模板下载")
    public void downLoadExcel(HttpServletResponse response) {
        ExcelUtils.exportTemplate(response, "用户表", NetworkSalesVolumeCreateValidate.class);
    }

    @CrossOrigin("*")
    @Log(title = "excel导入")
    @PostMapping("/importExcel")
    @ApiOperation(value="excel导入")
    public AjaxResult<Object> importExcel(@RequestParam("file") MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> iterator = sheet.iterator();
            System.out.println(iterator);
            while (iterator.hasNext()) {
                NetworkSalesVolumeCreateValidate networkSalesVolumeCreateValidate = new NetworkSalesVolumeCreateValidate();
                Row next = iterator.next();
                if (next.getRowNum() != 0) {
                    networkSalesVolumeCreateValidate.setClientName(next.getCell(0).getStringCellValue());
                    if (next.getCell(1).getStringCellValue().equals("未分配")){
                        networkSalesVolumeCreateValidate.setState(0);
                    }else if(next.getCell(1).getStringCellValue().equals("已分配")){
                        networkSalesVolumeCreateValidate.setState(1);
                    }else {
                        networkSalesVolumeCreateValidate.setState(2);
                    }
                    networkSalesVolumeCreateValidate.setClientSource(next.getCell(2).getStringCellValue());
                    networkSalesVolumeCreateValidate.setBelongIndustry(next.getCell(3).getStringCellValue());
                    networkSalesVolumeCreateValidate.setAdvisoryService(next.getCell(4).getStringCellValue());
                    networkSalesVolumeCreateValidate.setBusinessPrice(BigDecimal.valueOf(next.getCell(5).getNumericCellValue()));
                    networkSalesVolumeCreateValidate.setContacts(next.getCell(6).getStringCellValue());
                    networkSalesVolumeCreateValidate.setPost(next.getCell(7).getStringCellValue());
                    BigDecimal bd = new BigDecimal(String.valueOf(next.getCell(8).getNumericCellValue()));//要修改的值，需要string类型
                    String phoneNumber=bd.setScale(0,BigDecimal.ROUND_HALF_UP).toPlainString();
                    networkSalesVolumeCreateValidate.setPhone(phoneNumber);
                    networkSalesVolumeCreateValidate.setProvince(next.getCell(9).getStringCellValue());
                    networkSalesVolumeCreateValidate.setCity(next.getCell(10).getStringCellValue());
                    networkSalesVolumeCreateValidate.setDistrict(next.getCell(11).getStringCellValue());
                    networkSalesVolumeCreateValidate.setSalesman(next.getCell(12).getStringCellValue());
                    networkSalesVolumeCreateValidate.setOperateTime(new Date());
                    iNetworkSalesVolumeService.add(networkSalesVolumeCreateValidate);
                }
            }
            return AjaxResult.success();
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.success();
        }


    }

    @Log(title = "excel导出")
    @GetMapping("/exportExcel")
    @ApiOperation(value="excel导出")
    public void exportExcel(HttpServletResponse response) {
        List<NetworkSalesVolumeListedExport> list = iNetworkSalesVolumeService.list();
        ExcelUtils.export(response,"网销客户",list,NetworkSalesVolumeListedExport.class);
    }
}
